package go_grpc

import (
	"context"
	"fmt"
	"go_init/src/opt_rpc/go_grpc/api"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/protobuf/proto"
	"log"
	"net"
)

type IService struct {
	api.UnimplementedGreeterServer
}

func (service *IService) SendGrpc(ctx context.Context, in *api.SearchRequest) (reply *api.HelloReply, err error) {
	fmt.Println("============", in)
	return &api.HelloReply{Message: "Success", Code: 200, Body: make([]byte, 10)}, nil
}
func grpc_server() {
	listen, err := net.Listen("tcp", ":1024")
	if err != nil {
		log.Panicln("listen 1024 port is err ", err)
	}
	grpc_server := grpc.NewServer()

	api.RegisterGreeterServer(grpc_server, &IService{})

	err = grpc_server.Serve(listen)

	if err != nil {
		fmt.Println("failed to listen ", err)
		return
	}
}

func grpc_client() {
	dial, _ := grpc.Dial("localhost:1024", grpc.WithTransportCredentials(insecure.NewCredentials()))
	defer dial.Close()

	client := api.NewGreeterClient(dial)
	sendGrpc, err := client.SendGrpc(context.Background(), &api.SearchRequest{
		Query:      "1",
		PageNumber: 2,
		Maps:       make(map[string]int32),
		StrArr:     make([]string, 0),
	})

	if err != nil {
		log.Println("find a err ", err)
	}
	marshal, err := proto.Marshal(sendGrpc)
	if err != nil {
		log.Panicln("serialize fail ", err)
	}
	fmt.Println("======marshal", string(marshal))

	fmt.Println("==========", sendGrpc)
}
